﻿using H.Logs;
using H.Utils;
using System;
using System.IO;

namespace H.Logger.Logs.Listeners
{
    /// <summary>
    /// 将日志写入到文件的日志信息监听器
    /// </summary>
    public class HFileLogListener : ILogListener
    {
        /// <summary>
        /// 写入日志的流转换器
        /// </summary>
        private readonly StreamWriter _StreamWriter;

        /// <summary>
        /// 初始化一个日志接收器
        /// </summary>
        /// <param name="file"></param>
        public HFileLogListener(string logDir, string filePrefix)
        {
            Directory.CreateDirectory(logDir);

            string fileName = logDir + "\\" + filePrefix + DateTime.Now.Ticks + ".log";

            FileStream fs = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read);
            byte key = (byte)(new Random().Next() % 256);
            fs.WriteByte(key);

            _StreamWriter = new StreamWriter(fs.StreamXor(key)) { AutoFlush = true };
        }

        ///<inheritdoc/>
        public void Write(string str)
        {
            _StreamWriter.Write(str);
        }

        /// <summary>
        /// 是否已经释放资源
        /// </summary>
        private bool _IsDisposed = false;

        /// <summary>
        /// 关闭流
        /// </summary>
        /// <param name="disposing"></param>
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!_IsDisposed)
                {
                    _StreamWriter.Close();
                    _IsDisposed = true;
                }
            }
        }

        ///<inheritdoc/>
        public void Dispose()
        {
            Dispose(true);
        }

        ~HFileLogListener()
        {
            Dispose(false);
        }

    }
}
